#ifndef HTTPMANAGE_H
#define HTTPMANAGE_H

#include"Singleton.h"
#include<QUrl>
#include<QObject>
#include<QNetworkAccessManager>
#include<QJsonObject>
#include<QJsonDocument>
#include<QHttpMultiPart>
#include<QQueue>
#include<QMutex>
#include<QElapsedTimer>
#define UPLOAD_PROGRESS_SUFFIX ".progress"
//CRTP
class HttpManage:public QObject, public Singleton<HttpManage>, public std::enable_shared_from_this<HttpManage>
{
    Q_OBJECT
public:
    void PostHttpReq(QUrl url,QJsonObject json,ReqId req_id,Modules mod);
    void PostHttpMultiPartReq(QUrl url, QString header , QString body,ReqId req_id , Modules mod);
    QNetworkAccessManager& getManager();
    void setToken(const QString& token);
    void SetAuthInfo(const QString& token, QString uid , QString user);
    QString getUser();
    QString getToken();
    QString getUid();

    QNetworkReply* RangeRequest(QUrl url, qint64 startByte);
    void startChunkedUpload(const QString &filePath, const QUrl &url, qint64 chunkSize);

    ~HttpManage();

    // 新增槽函数：在主线程执行实际请求
    void handleUpload(QUrl url, QString header, QByteArray body, ReqId req_id , Modules mod);

    void handleDownload(QUrl url, QString header, QByteArray body, ReqId req_id , Modules mod);

    void showFileList(QUrl url);

private:
    friend class Singleton<HttpManage>;
    HttpManage();
private:
    QNetworkAccessManager _manager;
    QString _token;
    QString _uid;
    QString _user;
private slots:
    void slot_http_finish(ReqId id,QString res ,ErrorCode err,Modules mod);
signals:
    void sig_http_finish(ReqId id,QString res ,ErrorCode err,Modules mod);
    //Token 过期信号
    void sig_token_expired();

    void sig_reg_mod_finish(ReqId id,QString res,ErrorCode err);
    void sig_getback_mod_finish(ReqId id,QString res,ErrorCode err);
    void sig_login_mod_finish(ReqId id , QString res ,ErrorCode err);
    void sig_upload_mod_finish(ReqId id , QString res ,ErrorCode err);
    void sig_download_mod_finish(ReqId id , QString res ,ErrorCode err);

    void sig_file_list_received(QVector<QJsonValue> fielList, ErrorCode error);

    // 新增信号：请求转发到主线程
    void uploadRequested(QUrl url, QString header, QByteArray body, ReqId req_id , Modules mod);
};

#endif // HTTPMANAGE_H
